/**
 * 版权所有(C)，上海勾芒信息科技，2017，所有权利保留。
 * 
 * 项目名：	cards-web
 * 文件名：	WxAppUserServiceImpl.java
 * 模块说明：	
 * 修改历史：
 * 2017年4月13日 - Debenson - 创建。
 */
package cn.binarywang.wx.miniapp.api.impl;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gomore.jeecg.common.Assert;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;

import cn.binarywang.wx.miniapp.api.WxMaServiceEx;
import cn.binarywang.wx.miniapp.api.WxMaUserServiceEx;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.JsonMapper;

/**
 * @author Debenson
 * @since 0.1
 */
public class WxMaUserServiceExImpl extends WxMaUserServiceImpl implements WxMaUserServiceEx {
  static final Logger logger = LoggerFactory.getLogger(WxMaUserServiceExImpl.class);

  private final WxMaServiceEx maService;

  public WxMaUserServiceExImpl(WxMaServiceEx wxMaService) {
    super(wxMaService);
    this.maService = wxMaService;
  }

  @Override
  public WxMaJscode2SessionResult getSessionInfo(String code, String componentAppId,
      String componentAccessToken) throws WxErrorException {
    Assert.assertArgumentNotEmpty(code, "code");
    Assert.assertArgumentNotEmpty(componentAppId, "componentAppId");
    Assert.assertArgumentNotEmpty(componentAccessToken, "componentAccessToken");

    WxMaConfig config = maService.getWxMaConfig();
    Map<String, Object> params = Maps.newHashMap();
    params.put("appid", config.getAppid());
    params.put("js_code", code);
    params.put("grant_type", "authorization_code");
    params.put("component_appid", componentAppId);
    params.put("component_access_token", componentAccessToken);

    String url = "https://api.weixin.qq.com/sns/component/jscode2session";
    String response = maService.get(url, Joiner.on("&").withKeyValueSeparator("=").join(params));
    return WxMaJscode2SessionResult.fromJson(response);
  }

}
